package com.kmxd.ams.infra.tmpl.util;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.kmxd.ams.core.common.field.ExtField;
import com.kmxd.ams.infra.arrange.entity.Document;
import com.kmxd.ams.infra.tmpl.dto.JsonFieldDto;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.ibatis.type.JdbcType;

/**
 * 获取扩展字段工具类
 *
 * @author ZuoLG
 */
@Slf4j
public class ExtFieldUtil {

  /** 获取扩展字段 */
  public static List<JsonFieldDto> getExtField(Class<?> clazz) {
    if (ObjectUtil.isNull(clazz)) {
      return Lists.newArrayList();
    }
    List<Field> fieldList = ReflectionKit.getFieldList(ClassUtils.getUserClass(clazz));
    return fieldList.stream()
        .filter(
            field -> {
              ExtField tableField = field.getAnnotation(ExtField.class);
              return (tableField != null);
            })
        .map(
            field -> {
              ExtField tableField = field.getAnnotation(ExtField.class);
              JsonFieldDto jsonFieldDto = new JsonFieldDto();
              jsonFieldDto.setCode(tableField.value());
              jsonFieldDto.setName(tableField.desc());
              jsonFieldDto.setType(
                  tableField.jdbcType().name().equalsIgnoreCase(JdbcType.TIME.name())
                      ? "datetime"
                      : tableField.jdbcType().name());
              jsonFieldDto.setLength(tableField.length() == 0 ? null : tableField.length());
              jsonFieldDto.setSort(9999);
              return jsonFieldDto;
            })
        .collect(Collectors.toList());
  }

  public static void main(String[] args) {
    List<JsonFieldDto> extFields = ExtFieldUtil.getExtField(Document.class);
    log.info("========" + extFields.toString());
  }
}
